package com.deng.api.log;

import com.deng.api.entity.SysLog;
import com.deng.api.mapper.SysLogMapper;
import com.deng.commons.utils.IPUtils;
import com.deng.commons.utils.UserUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 日志注解解析
 *
 * 切面：
 *      （1）定义切入点
 *      （2）定义通知： 前置通知、环绕通知、后置通知、异常通知、最终通知
 */
@Component
@Aspect
public class LogAspect {

    @Resource
    private SysLogMapper sysLogMapper;

    /**
     * 监听添加了@Log注解的方法执行
     */
    @Pointcut("@annotation(com.deng.api.log.Log)")
    public void logPointCut(){

    }

    /**
     * 环绕通知
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //保存操作日志
       SysLog sysLog = new SysLog();
       //操作人
        sysLog.setUsername(UserUtils.getUser().getUsername());
        //请求时间
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        sysLog.setTime(System.currentTimeMillis()-startTime);
        //描述
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Log log =  method.getAnnotation(Log.class);
        sysLog.setDescription(log.value());
        //请求方法
        String methodName = joinPoint.getTarget().getClass().getName()+"."+methodSignature.getName();
        sysLog.setMethod(methodName);
        //IP、浏览器、address
        HttpServletRequest request =
                ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        sysLog.setRequestIp(IPUtils.getIp(request));
        sysLog.setBrowser(IPUtils.getBrowser(request));
        sysLog.setAddress(IPUtils.getCityInfo(sysLog.getRequestIp(),true));
        //保存数据到数据库
        sysLogMapper.insert(sysLog);
        return result;
    }

    /**
     * 异常通知
     */
//    @AfterThrowing
//    public void afterThrowing(){
//
//    }

}
